package io.gitee.wl4837.alatool.core.validate.validator;

import io.gitee.wl4837.alatool.core.validate.*;
import io.gitee.wl4837.alatool.core.validate.result.FormValidateError;
import io.gitee.wl4837.alatool.core.validate.result.FormValidateSuccess;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator implements FormValidator {

    private static final String EMAIL_PATTERN =
            "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" +
                    "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN);

    public static boolean validate(final String email) {
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    @Override
    public FormValidateResult handle(Object data, FormValidateRuleData formValidateRuleData) {
        if (null == data) {
            if (formValidateRuleData.getRequired()) {
                return new FormValidateError(formValidateRuleData.getMessage());
            } else {
                return new FormValidateSuccess();
            }
        }
        String email = data.toString();
        if ("".equals(email)) {
            if (formValidateRuleData.getRequired()) {
                return new FormValidateError(formValidateRuleData.getMessage());
            } else {
                return new FormValidateSuccess();
            }
        }
        if (validate(email)) {
            return new FormValidateSuccess();
        } else {
            return new FormValidateError(formValidateRuleData.getMessage());
        }
    }

}
